/**创建活动 */
import React, { useState, useEffect } from 'react';
import { useLocation, useHistory } from 'umi';

import { Button, Form, Progress, message } from 'antd';
import moment from 'moment';

import EssentialInformation from './components/EssentialInformation';
import ActiveOption from './components/ActiveOption';
import SignUp from './components/SignUp';
import Vote from './components/Vote';
import AdmissionTicket from './components/AdmissionTicket';
import SignIn from './components/SignIn';
import LuckDraw from './components/LuckDraw';
import { loginApi } from '@/api/login';
import { addActivityUrl, saveDraftsUrl, queryByUpdateUrl } from '@/urls/url';
import styles from './index.less';
import { queryAddressForFourLinkageUrl } from '@/urls/url';

const AddActivity = () => {
  const history = useHistory();
  const location: any = useLocation();

  const [EssentialInformationForm] = Form.useForm();
  const [SignUpForm] = Form.useForm();
  const [VoteForm] = Form.useForm();

  /**
   * 活动选择
   */
  const [selected, setSelected] = useState<number[]>([]);
  /**
   * 活动图
   */
  const [activityStatus, setActivityStatus] = useState(false);
  /**
   * 缩略图
   */
  interface Option {
    value: string;
    label: string;
    children?: Option[];
    isLeaf?: boolean;
    loading?: boolean;
  }
  const [abbreviationstatus, setAbbreviationStatus] = useState(false);

  const [options, setOptions] = useState<Option[]>([]);

  /** 城市 级联 */

  const getQueryAddressForFourLinkage = async () => {
    const {
      data: { data },
    } = await loginApi(queryAddressForFourLinkageUrl, {
      addressLevel: 1,
    });
    const newData: any = data.map((item: any) => ({
      value: item.addressCode,
      label: item.addressName,
      isLeaf: false,
    }));
    setOptions(newData);
  };

  const loadData: any = (selectedOptions: Option[]) => {
    const targetOption = selectedOptions[selectedOptions.length - 1];

    targetOption.loading = true;

    // load options lazily
    setTimeout(async () => {
      targetOption.loading = false;
      const {
        data: { data },
      } = await loginApi(queryAddressForFourLinkageUrl, {
        addressLevel: 2,
        parentId: targetOption.value,
      });
      targetOption.children = data.map((item: any) => ({
        value: item.addressCode,
        label: item.addressName,
      }));

      setOptions([...options]);
    }, 1000);
  };

  /**
   *
   * 数据回填，编辑功能
   */
  const getData = async () => {
    const {
      data: { data },
    } = await loginApi(queryByUpdateUrl, {
      activityBasicId: location.query.activityBasicId,
    });
    console.log(data);

    const {
      activityName,
      activityContent,
      activitySite,
      activityOrganizers,
      startDate,
      endDate,
      pictureKey,
      pictureUrl,
      thumbnailPictureKey,
      thumbnailPictureUrl,
      provinceCode,
      cityCode,
      isSignUp,
      isVote,
      isRobTickets,
      isSignIn,
      isLuckyDraw,
      scheduleVOS,
      activityVOS,
    } = data;

    /**获取一级城市数据 */
    const getProvinceCodeData = await loginApi(queryAddressForFourLinkageUrl, {
      addressLevel: 1,
    });
    /**获取二级城市数据 */
    const getCityCodeData = await loginApi(queryAddressForFourLinkageUrl, {
      addressLevel: 2,
      parentId: provinceCode,
    });
    /**用数据回填的一级城市code查找对应的索引 */
    const index = getProvinceCodeData.data.data.findIndex(
      (item: any) => item.addressCode === provinceCode,
    );
    /**修改一级城市数据结构，做渲染用 */
    const newData = getProvinceCodeData.data.data.map((obj: any) => ({
      value: obj.addressCode,
      label: obj.addressName,
      isLeaf: false,
    }));
    /**将二级城市的数据转换完结构后，添加到一级城市的children上 */
    newData[index].children = getCityCodeData.data.data.map((item: any) => ({
      value: item.addressCode,
      label: item.addressName,
    }));
    setOptions(newData);

    {
      isSignUp && setSelected((val) => [...val, 1]);
    }
    {
      isVote && setSelected((val) => [...val, 2]);
    }
    {
      pictureKey && setAbbreviationStatus(true);
    }
    {
      thumbnailPictureKey && setActivityStatus(true);
    }

    EssentialInformationForm.setFieldsValue({
      activityName,
      activityContent,
      activitySite,
      activityOrganizers,
      date: [moment(startDate), moment(endDate)],
      picture: [
        {
          uid: 'picture',
          key: pictureKey,
          url: pictureUrl,
        },
      ],
      thumbnailPicture: [
        {
          uid: 'thumbnailPicture',
          key: thumbnailPictureKey,
          url: thumbnailPictureUrl,
        },
      ],
      provinceCode: [provinceCode, cityCode],

      scheduleVOS: scheduleVOS.map(
        (item: { scheduleName: any; scheduleDate: moment.MomentInput }) => {
          return {
            scheduleName: item.scheduleName,
            scheduleDate: moment(item.scheduleDate),
          };
        },
      ),
    });
    {
      isSignUp &&
        SignUpForm.setFieldsValue({
          signUpDate: [
            moment(activityVOS[0].startDate),
            moment(activityVOS[0].endDate),
          ],
          numberLimit: activityVOS[0].numberLimit,
          requiredEntryForms: activityVOS[0].requiredEntryForms.map(
            (item: { key: string }) => item.key,
          ),
          optionalEntryForms: activityVOS[0].optionalEntryForms[0].key,
          signUp: activityVOS[0].optionalEntryForms
            .filter((_item: any, index: number) => {
              return index !== 0;
            })
            .map((item: { key: string }) => {
              return { optionalEntryForms: item.key };
            }),
        });
    }
    const voteValue = (id: number) => {
      return {
        voteDate: [
          moment(activityVOS[id].startDate),
          moment(activityVOS[id].endDate),
        ],
        voteWay: String(activityVOS[id].voteWay),
        // dayVoteLimit,
        // singlePlayerLimit,
        voteObjectVOS: activityVOS[id].voteObjectVOS
          .filter((_item: any, index: number) => {
            return index !== 0;
          })
          .map(
            (item: {
              name: any;
              instructions: any;
              id: any;
              pictureKey: any;
              pictureUrl: any;
            }) => {
              return {
                name: item.name,
                instructions: item.instructions,
                votePicture: [
                  {
                    uid: item.id,
                    key: item.pictureKey,
                    url: item.pictureUrl,
                  },
                ],
              };
            },
          ),
        name: activityVOS[id].voteObjectVOS[0].name,
        instructions: activityVOS[id].voteObjectVOS[0].instructions,
        votePicture: [
          {
            uid: 'votePicture',
            key: activityVOS[id].voteObjectVOS[0].pictureKey,
            url: activityVOS[id].voteObjectVOS[0].pictureUrl,
          },
        ],
      };
    };
    if (isSignUp && isVote) {
      VoteForm.setFieldsValue(voteValue(1));
    } else if (isVote) {
      VoteForm.setFieldsValue(voteValue(0));
    }
  };
  useEffect(() => {
    if (location.query.activityBasicId) {
      getData();
    } else {
      getQueryAddressForFourLinkage();
    }
  }, []);

  /**
   * 进度条状态
   */
  const [percent, setPercent] = useState(50);

  /**
   * 发布
   */
  const release = async () => {
    console.log('发布');
  };
  /**
   * 下一步
   */
  const nextStep = async () => {
    const res = await EssentialInformationForm.validateFields();
    console.log(res);
    setPercent(100);
  };
  /**
   * 上一步
   */
  const Back = () => {
    setPercent(50);
  };
  /**
   * 预览
   */
  const preview = async () => {
    console.log('预览');
    const res = await VoteForm.getFieldsValue();
    console.log(res);
  };
  /**
   * 保存草稿
   */
  const SaveDraft = async (activityBasicId = '') => {
    if (percent === 100) {
      const {
        activityName,
        activityContent,
        activitySite,
        activityOrganizers,
        date,
        picture,
        thumbnailPicture,
        provinceCode,
        scheduleVOS,
      } = EssentialInformationForm.getFieldsValue();

      const {
        signUpDate,
        numberLimit,
        requiredEntryForms,
        optionalEntryForms,
        signUp,
      } = SignUpForm.getFieldsValue();

      const {
        voteDate,
        voteWay,
        dayVoteLimit,
        singlePlayerLimit,
        voteObjectVOS,
        name,
        instructions,
        votePicture,
      } = VoteForm.getFieldsValue();

      if (selected.length > 0) {
        const aa: number[] = [];
        const obj = {
          key: '姓名',
          value: '',
          inputType: 1,
          length: 30,
          inputVerifyType: 'BaseInput7',
        };
        const activityVOS = [];
        //做完表单验证的标记
        if (selected.indexOf(1) > -1) {
          activityVOS.push({
            activityType: 1,
            startDate: moment(signUpDate[0]).format('YYYY-MM-DD HH:mm:ss'),
            endDate: moment(signUpDate[1]).format('YYYY-MM-DD HH:mm:ss'),
            numberLimit: numberLimit && numberLimit,
            requiredEntryForms: requiredEntryForms.map((item: any) => {
              return {
                ...obj,
                key: item,
              };
            }),
            optionalEntryForms: signUp
              ? [
                  {
                    key: optionalEntryForms,
                    value: '',
                    inputType: 1,
                    length: 30,
                    inputVerifyType: 'BaseInput7',
                  },
                ].concat(
                  signUp.map((item: any) => {
                    return {
                      ...obj,
                      key: item.optionalEntryForms,
                    };
                  }),
                )
              : [
                  {
                    key: optionalEntryForms,
                    value: '',
                    inputType: 1,
                    length: 30,
                    inputVerifyType: 'BaseInput7',
                  },
                ],
          });
          await SignUpForm.validateFields()
            .then(() => aa.push(1))
            .catch(() => aa.push(0));
        }

        if (selected.indexOf(2) > -1) {
          activityVOS.push({
            activityType: 2,
            startDate: moment(voteDate[0]).format('YYYY-MM-DD HH:mm:ss'),
            endDate: moment(voteDate[1]).format('YYYY-MM-DD HH:mm:ss'),
            voteWay,
            dayVoteLimit: dayVoteLimit && dayVoteLimit,
            singlePlayerLimit: singlePlayerLimit && singlePlayerLimit,
            voteObjectVOS: voteObjectVOS
              ? [
                  {
                    instructions: instructions,
                    pictureKey: votePicture[0].response
                      ? votePicture[0].response.data.imgKey
                      : votePicture[0].key,
                    pictureUrl: votePicture[0].response
                      ? votePicture[0].response.data.imgUrl
                      : votePicture[0].url,
                    name: name,
                  },
                ].concat(
                  voteObjectVOS.map((item: any) => {
                    return {
                      instructions: item.instructions,
                      pictureKey: item.votePicture[0].response
                        ? item.votePicture[0].response.data.imgKey
                        : item.votePicture[0].key,
                      pictureUrl: item.votePicture[0].response
                        ? item.votePicture[0].response.data.imgUrl
                        : item.votePicture[0].url,
                      name: item.name,
                    };
                  }),
                )
              : [
                  {
                    instructions: instructions,
                    pictureKey: votePicture[0].response
                      ? votePicture[0].response.data.imgKey
                      : votePicture[0].key,
                    pictureUrl: votePicture[0].response
                      ? votePicture[0].response.data.imgUrl
                      : votePicture[0].url,
                    name: name,
                  },
                ],
          });
          await VoteForm.validateFields()
            .then(() => aa.push(1))
            .catch(() => aa.push(0));
        }
        if (aa.indexOf(0) === -1) {
          const res = await loginApi(saveDraftsUrl, {
            activityBasicId,
            activityName,
            activityContent,
            activitySite: activitySite && activitySite,
            activityOrganizers: activityOrganizers && activityOrganizers,
            startDate: moment(date[0]).format('YYYY-MM-DD HH:mm:ss'),
            endDate: moment(date[1]).format('YYYY-MM-DD HH:mm:ss'),
            //判断回填的图片数据还是新增加图片数据
            pictureKey: picture[0].response
              ? picture[0].response.data.imgKey
              : picture[0].key,
            pictureUrl: picture[0].response
              ? picture[0].response.data.imgUrl
              : picture[0].url,
            thumbnailPictureKey: thumbnailPicture[0].response
              ? thumbnailPicture[0].response.data.imgKey
              : thumbnailPicture[0].key,
            thumbnailPictureUrl: thumbnailPicture[0].response
              ? thumbnailPicture[0].response.data.imgUrl
              : thumbnailPicture[0].url,
            provinceCode: provinceCode[0],
            cityCode: provinceCode[1],
            isSignUp: selected.indexOf(1) > -1 && true,
            isVote: selected.indexOf(2) > -1 && true,
            isRobTickets: selected.indexOf(3) > -1 && true,
            isSignIn: selected.indexOf(4) > -1 && true,
            isLuckyDraw: selected.indexOf(5) > -1 && true,
            scheduleVOS: scheduleVOS && scheduleVOS,
            activityVOS: activityVOS,
          });
          if (res.data.message === '操作成功') {
            history.push('/createActivity');
            message.success('修改成功');
          } else {
            message.warning(res.data.message);
          }
          console.log(res);
        }
      } else {
        message.warning('请选择一个想要创建的活动');
      }
    } else {
      message.warning('请点击下一步');
    }
  };

  return (
    <div>
      <div
        style={{
          background: '#fff',
          padding: '20px 0 20px 20px',
          borderRadius: 10,
        }}
      >
        <div style={{ width: 500 }}>
          <div style={{ margin: '0 0 10px 0' }}>创建活动</div>
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              marginLeft: 10,
            }}
          >
            <div
              style={{
                width: 10,
                height: 10,
                borderRadius: 5,
                background: '#1890ff',
                marginRight: 4,
              }}
            />
            <Progress
              percent={percent}
              status="active"
              showInfo={false}
              style={{ marginBottom: 3 }}
            />
            <div
              style={{
                width: 10,
                height: 10,
                borderRadius: 5,
                background: '#1890ff',
                marginLeft: 4,
              }}
            />
          </div>
          <div
            style={{
              display: 'flex',
              justifyContent: 'space-between',
            }}
          >
            <span>基本信息</span>
            <span>活动信息</span>
          </div>
        </div>
      </div>
      <div className={percent === 100 ? '' : styles['display-style']}>
        <ActiveOption selected={selected} setSelected={setSelected} />
      </div>
      <div
        style={{
          marginTop: 20,
          background: '#fff',
          padding: 24,
          borderRadius: 10,
        }}
      >
        <div className={percent === 100 ? styles['display-style'] : ''}>
          <EssentialInformation
            EssentialInformationForm={EssentialInformationForm}
            abbreviationstatus={abbreviationstatus}
            setAbbreviationStatus={setAbbreviationStatus}
            activityStatus={activityStatus}
            setActivityStatus={setActivityStatus}
            options={options}
            loadData={loadData}
          />
        </div>

        {percent === 100 && (
          <>
            <div
              className={
                selected.indexOf(1) > -1 ? '' : styles['display-style']
              }
            >
              <SignUp SignUpForm={SignUpForm} />
            </div>
            <div
              className={
                selected.indexOf(2) > -1 ? '' : styles['display-style']
              }
            >
              <Vote VoteForm={VoteForm} />
            </div>
            <div
              className={
                selected.indexOf(3) > -1 ? '' : styles['display-style']
              }
            >
              <AdmissionTicket />
            </div>
            <div
              className={
                selected.indexOf(4) > -1 ? '' : styles['display-style']
              }
            >
              <SignIn />
            </div>
            <div
              className={
                selected.indexOf(5) > -1 ? '' : styles['display-style']
              }
            >
              <LuckDraw />
            </div>
            {}
            <Button
              type="primary"
              onClick={release}
              style={{ marginRight: 10 }}
            >
              发布
            </Button>
          </>
        )}
        {percent === 100 ? (
          <Button type="primary" onClick={Back} style={{ marginRight: 10 }}>
            上一步
          </Button>
        ) : (
          <Button type="primary" onClick={nextStep} style={{ marginRight: 10 }}>
            下一步
          </Button>
        )}
        <Button onClick={preview} style={{ marginRight: 10 }}>
          预览
        </Button>
        <Button
          onClick={() => SaveDraft(location.query.activityBasicId)}
          style={{ marginRight: 10 }}
        >
          保存草稿
        </Button>
      </div>
    </div>
  );
};
export default AddActivity;
